# Stratego utility functions
# Purpose: Wrap Stratego transform calls
# Author:  Wouter Caarls
# Date:    05-11-2004

import os, string, subprocess
from aterm import *

def readall(f):
  """Read an entire multi-line file into a single string,
     deleting newlines"""
  res = []
  for line in f:
    res.append(line)

  return "".join(res)

def FreeTransform(t, strategy):
  """Transform a string into a string using strategy"""
  p = subprocess.Popen(strategy, shell=True,
                       stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
  (fr, err) = p.communicate(t)  
  
  if p.returncode:
    return None
  else:
    return fr

def Transform(t, strategy):
  """Transform an ATerm into an ATerm using strategy"""
  if not isinstance(t,  ATerm):
    t = ParseATerm(t)

  return ParseATerm(FreeTransform(str(t), strategy))

def Parse(s, strategy):
  """Parse a string into an ATerm using strategy"""
  if type(s) != str:
    s = str(s)

  return ParseATerm(FreeTransform(s, strategy))

def Unparse(t, strategy):
  """Unparse an ATerm into a string using strategy"""
  if not isinstance(t, ATerm):
    t = ParseATerm(t)

  return FreeTransform(str(t), strategy)

def ParseC(s):
  """Parse a c program into an ATerm"""
  return Parse(s, "parse-p")

def PPC(t):
  """Prettyprint an ATerm tree into a c program"""
  return Unparse(t, "pp-p")
